package org.webbase.system.web;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.webbase.common.JsonResult;
import org.webbase.system.pojo.Journal;
import org.webbase.system.service.JournalService;

@Controller
@RequestMapping(value="/system/journal")
public class JournalAction extends BaseAction{
	
	private static final Logger logger = LogManager.getLogger(JournalAction.class);
	private static final String[] logLevel = {"error","warn","info","debug"};
	
	@Autowired private JournalService journalService;
	
	@RequestMapping(method=RequestMethod.GET)
	public String list(){
		return "system/journal/journal-lists";
	}
	
	/**
	 * 根据日志级别和时间进行筛选日志文件
	 * @param journal
	 * @return
	 */
	@RequestMapping(value="/query",method=RequestMethod.POST)
	@ResponseBody
	public JsonResult query(Journal journal) {
		StringBuilder sb = new StringBuilder();
		journal = checkInvalidParam(journal,"yyyy-MM");
		if( journal == null ){
			return result(-1,"请选择正确的日志级别（error、warn、info、debug）和正确的日期格式（yyyy-MM,2016-06）");
		}else{
			sb.append("  log level=");
			sb.append(journal.getLevelName());
			sb.append("  date=");
			sb.append(journal.getDateLog());
			logger.debug(sb.toString());
			List<Journal> journalList = journalService.query(journal.getLevelName(), journal.getDateLog());
			return result(200,"success",journalList);
		}
		
	}
	@RequestMapping(value="/query",method=RequestMethod.GET)
	public String query(){
		return "system/journal/journal-list";
	}
	
	@RequestMapping(value="/check",method=RequestMethod.POST)
	@ResponseBody
	public JsonResult check(Journal journal){
		StringBuilder sb = new StringBuilder();
		journal = checkInvalidParam(journal, "yyyy-MM-dd");
		if( journal == null){
			return result(-1,"请选择正确的日志级别（error、warn、info、debug）和正确的日期格式（yyyy-MM-dd,2016-06-01）");
		}else{
			sb.append("  log level=");
			sb.append(journal.getLevelName());
			sb.append("  date=");
			sb.append(journal.getDateLog());
			logger.debug(sb.toString());
			String content = journalService.check(journal.getLevelName(), journal.getDateLog());
			return result(200,"success",content);
		}
	}
	
	@RequestMapping(value="/check",method=RequestMethod.GET)
	public String check(){
		return "system/journal/journal-check";
	}
	/**
	 * 判断参数的合法性
	 * @param journal
	 * @param format
	 * @return
	 */
	private Journal checkInvalidParam(Journal journal, String format){
		if(!StringUtils.isEmpty(journal.getLevelName())){
			if(!this.checkLevel(journal.getLevelName())){
				return null;
			}
		}else{
			journal.setLevelName("error");
		}
		if(!StringUtils.isEmpty(journal.getDateLog())){
			if(!this.checkDateFormat(journal.getDateLog(),format)){
				return null;
			}
		}else{
			Date date = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
			journal.setDateLog(sdf.format(date));
		}
		return journal;
	}
	
	/**
	 * 检查日志级别是否符合要求
	 * @param level
	 * @return
	 */
	private boolean checkLevel(String level){
		for (String string : logLevel) {
			if(string.equals(level)){
				return true;
			}
		}
		return false;
	}
	/**
	 * 检测 日期格式是否正确， yyyy-MM 2016-06
	 * @param date			日期字符串
	 * @return
	 */
	private boolean checkDateFormat(String date){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		try {
			sdf.parse(date);
			return true;
		} catch (ParseException e) {
			return false;
		}
	}
	
	/**
	 * 检测 日期格式是否正确， format
	 * @param date
	 * @param format
	 * @return
	 */
	private boolean checkDateFormat(String date, String format){
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		try {
			sdf.parse(date);
			return true;
		} catch (ParseException e) {
			return false;
		}
	}
	
}
